﻿using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Web;

namespace SlamCms.SharePoint.UtilityPages
{
	public partial class ClearList : LayoutsPageBase
	{
		protected void Page_Load(object sender, EventArgs e)
		{
			if (Request.QueryString["ListID"] != null)
			{
				Guid listId = Guid.Empty;
				try
				{	
					listId = new Guid(Request.QueryString["ListID"].TrimStart('{').TrimEnd('}'));
				}
				catch { }

				if (listId != Guid.Empty)
				{
					bool listFound = false;
					string listName = "";
					SPSite currentSite = SPControl.GetContextSite(HttpContext.Current);
					SPSecurity.RunWithElevatedPrivileges(delegate()
					{
						using (SPSite siteCollection = new SPSite(currentSite.ID))
						{
							foreach (SPWeb site in siteCollection.AllWebs)
							{
								SPList list = null;
								try
								{
									list = site.Lists[listId];
								}
								catch { }

								if (list != null)
								{
									listFound = true;
									site.AllowUnsafeUpdates = true;
									while (list.Items.Count > 0)
									{
										list.Items[0].Delete();
									}
									listName = list.Title;
									site.AllowUnsafeUpdates = false;
								}
								
								site.Dispose();
							}
						}
					});

					if (!listFound)
					{
						ltMessage.Text = Request.QueryString["ListID"] + " does not match a List in this Site Collection";
					}
					else
					{
						ltMessage.Text = listName + " has been cleared of items";
					}
				}
				else
				{
					ltMessage.Text = Request.QueryString["ListID"] + " is not a valid Guid";
				}
			}
		}
	}
}
